
import pyaudio

def get_available_voice_devices():
    p = pyaudio.PyAudio()

    # 先列出所有可用的音频输入设备
    info = p.get_host_api_info_by_index(0)
    num_devices = info.get('deviceCount')
    input_device_index = None

    print("可用的音频输入设备：")
    for i in range(num_devices):
        device_info = p.get_device_info_by_host_api_device_index(0, i)
        if device_info.get('maxInputChannels') > 0:  # 只显示有输入通道的设备
            print(f"设备{i}: {device_info.get('name')}")
            if "USB" in device_info.get('name'):
                input_device_index = i

    if input_device_index is not None:
        return input_device_index


def show_device_parameters(input_device_index):
    p = pyaudio.PyAudio()
    if input_device_index is not None:
        device_info = p.get_device_info_by_host_api_device_index(0, input_device_index)
        device_rate = int(device_info.get('defaultSampleRate'))
        device_channels = device_info.get('maxInputChannels')
        print(f"使用设备: {device_info.get('name')}, 采样率: {device_rate}, 通道数: {device_channels}")

if __name__ == "__main__":
    get_available_voice_devices()
    # show_device_parameters(4)


# 编辑配置文件
# sudo vim /etc/pulse/daemon.conf

# 找到如下两行，默认采样率为44.1KHz 16bit
# ; default-sample-format = s16le
# ; default-sample-rate = 44100

# 修改为如下样子，注意取消“;”的注释
# 我这修改的是192KHz 24bit，详细说明见文章下方引用处
# default-sample-format = s24le
# default-sample-rate = 192000

# default-sample-format = s24le
# default-sample-rate = 16000


# 重启服务生效
# pulseaudio -k
# pulseaudio --start

# 用以下命令输出检查是否生效
# 生效应该可以找到：sample spec: s24le 2ch 192000Hz
# pacmd list-sinks


# 卸载已有的 null sink
# 首先查到模块号：
# pactl list modules short | grep module-null-sink

# 假设模块号为 17，执行：
# pactl unload-module 17


# 按需加载，并指定采样率
# pactl load-module module-null-sink \
#   sink_name=auto_null \
#   format=s16le \
#   rate=16000 \
#   channels=2


# 验证结果
# 再次执行：

# pacmd list-sinks